<!DOCTYPE html>
<script src="/forms-test-resources/common.js"></script>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<div id="container"></div>
<input type=file multiple>
<script type="module">
import {mockFileChooserFactory} from '/wpt_internal/forms/resources/mock-file-chooser.js';

class MyControl extends HTMLElement {
  static get formAssociated() { return true; }

  constructor() {
    super();
    this.internals_ = this.attachInternals();
    this.value_ = '';
  }

  get value() {
    return this.value_;
  }
  set value(fileOrString) {
    this.internals_.setFormValue(fileOrString);
    this.value_ = fileOrString;
  }
  setValues(nameValues) {
    const formData = new FormData();
    for (let p of nameValues) {
      formData.append(p[0], p[1]);
    }
    this.internals_.setFormValue(formData);
  }
}
customElements.define('my-control', MyControl);

function selectFilePromise(paths) {
  return new Promise((resolve, reject) => {
    mockFileChooserFactory.setPathsToBeChosen(paths);
    const file = document.querySelector('input[type=file]');
    file.addEventListener('change', () => { resolve(file) });
    clickElement(file);
    setTimeout(reject, 3000);
  });
}

function submitPromise(t) {
  return new Promise((resolve, reject) => {
    const iframe = document.querySelector('iframe');
    iframe.onload = () => resolve(iframe.contentWindow.location.search);
    iframe.onerror = () => reject();
    document.querySelector('form').submit();
  });
}

promise_test(async t => {
  $('container').innerHTML = '<form action="../external/wpt/common/blank.html" target="if1">' +
      '<input name=name-pd1 value="value-pd1">' +
      '<my-control name=ce1></my-control>' +
      '</form>' +
      '<iframe name="if1"></iframe>';
  const fileInput = await selectFilePromise(['../OWNERS']);
  document.querySelector('my-control').value = fileInput.files[0];
  return submitPromise(t).then(query => {
    assert_equals(query, '?name-pd1=value-pd1&ce1=OWNERS');
  });
}, 'Single value - A file value');

promise_test(async t => {
  $('container').innerHTML = '<form action="../external/wpt/common/blank.html" target="if1">' +
      '<my-control name=ce1></my-control>' +
      '</form>' +
      '<iframe name="if1"></iframe>';
  const fileInput = await selectFilePromise(['../OWNERS', '../PRESUBMIT.py']);
  document.querySelector('my-control').setValues(
      [['sub1', fileInput.files[0]], ['sub2', fileInput.files[1]]]);
  return submitPromise(t).then(query => {
    assert_equals(query, '?sub1=OWNERS&sub2=PRESUBMIT.py');
  });
}, 'Multiple values - file values');
</script>
